const app = getApp();
var common = require("../../resources/config/config.js");
var utils = require("../../utils/util.js");

// pages/order/order.js
Page({

  data: {
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var sport = '';
    var sportIndex=options.index;
    if(options.language=='en'){
      sport = app.globalData.sports_with_lang.en[sportIndex];
    }else{
      sport = app.globalData.sports_with_lang.zh[sportIndex];
    }

    var bookings = JSON.parse(options.booked)
    console.log(bookings);
    this.setData({
      language: options.language,
      date: options.date,
      sportId: options.sportId,
      sport:sport,
      index: options.index,
      booked: bookings,
      total: options.total,
      labels: ['迪卡侬运动场', '运动：', '日期：','场地：','总金额：¥','确认并支付']
    })
    console.log(this.data);

    if (this.data.language == 'EN') {
      this.setData({
        labels: ['China Lab Playground', 'Sport: ', 'Date: ','Playground: ','Total Price: ¥','Pay']
      })
    };
  },

  bindNavigate: function (e) {
    
    //open payment
    var data = [];
    var submitBookingUrl = common.getApiLink("bookSession");
    for (var i = 0; i < this.data.booked.length; i++) {
      var dataSub = {
        "bookingStatus": "CREATED",
        "cours": {
          "coursId": this.data.booked[i].courtsId
        },
        "end": this.data.date,
        "start": this.data.date,
        "time": this.data.booked[i].bookingTime,
        "userId": app.globalData.user.id
      };
      //data.push(dataSub);
      data=dataSub;
    }

    console.log(data);
    var self=this;
    utils.req(submitBookingUrl, data, function (res, status) {
      if (res.bookingid) {
        console.log("order id :" + res.bookingid);
        var x = '';
        x = '../payment/payment' + '?language=' + self.data.language + 
        '&orderId=' + res.bookingid + 
        '&total=' + self.data.total + 
          '&index=' + self.data.index +
          '&date=' + self.data.date +
        '&sportId=' + self.data.sportId+'';
        console.log(x);
        wx.navigateTo({
          url: x,
        });
      } else {
        console.log(res.errorcode);
        wx.showModal({
          title: 'Error',
          content: res.errorcode,
          success: function (res) {
            if (res.confirm) {
              console.log('Ok')
              var x = '';
              x = '../court/court' + '?language=' + self.data.language + '&date=' + self.data.date + '&index=' + self.data.index + "&sportId=" + self.data.sportId;
              console.log(x);
              wx.navigateTo({
                url: x,
              })
            } else if (res.cancel) {
              console.log('Cancel')
              wx.navigateTo({
                url: '../booking/booking',
              })
            }  
          },
          fail: function (res) {
            console.log(res.errMsg)
          }  
        })
      }
    });
  }
})